package com.mall.user.services;/**
 * Created by ciggar on 2019/7/30.
 */

import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/7/30-下午11:51
 */
@Slf4j
@Component
@Service
public class MemberServiceImpl implements IMemberService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

//    @Autowired  没用这个做验证，用的是member
//    IUserLoginService userLoginService;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * 根据用户id查询用户会员信息
     * @param request
     * @return
     */
    @Override
    public QueryMemberResponse queryMemberById(QueryMemberRequest request) {
        QueryMemberResponse queryMemberResponse=new QueryMemberResponse();
        try{
            request.requestCheck();
            Member member=memberMapper.selectByPrimaryKey(request.getUserId());
            if(member==null){
                queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            }
            queryMemberResponse=memberConverter.member2Res(member);
            queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("MemberServiceImpl.queryMemberById Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse,e);
        }
        return queryMemberResponse;
    }

    @Override
    public HeadImageResponse updateHeadImage(HeadImageRequest request) {
        HeadImageResponse response=new HeadImageResponse();
        //TODO
        return response;
    }

    @Override
    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
        return null;
    }

    @Override
    public UserLoginResponse userLogin(UserLoginRequest userLoginRequest) {

        UserLoginResponse userLoginResponse = new UserLoginResponse();

        try {
            //为什么在这里校验而不是用validator?代码风格的统一，方便用枚举类返回错误类型
            userLoginRequest.requestCheck();

            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username",userLoginRequest.getUserName())
                                    .andEqualTo("password",userLoginRequest.getPassword());
            List<Member> members = memberMapper.selectByExample(example);

            //登录失败的情况1:账号密码错误
            if(members.size() == 0)
            {
                userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR .getCode());
                userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR .getMessage());
                return userLoginResponse;
            }
            Member member = members.get(0);
            //失败情况2：未激活
            if("N".equals(member.getIsVerified()))
            {
                userLoginResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR  .getCode());
                userLoginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR  .getMessage());
                return userLoginResponse;
            }
            //登陆成功
            userLoginResponse = memberConverter.memberToUserLoginResponse(member);
            userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

            //生成JWT并放入
            String token = JwtTokenUtils.builder().msg(member.getUsername()).build().creatJwtToken();
            userLoginResponse.setToken(token);

        }catch (Exception e)
        {
            log.error("UserLoginException" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userLoginResponse,e);
        }
        return userLoginResponse;
    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {

        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();

        try {
            checkAuthRequest.requestCheck();

            String s = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build().freeJwt();
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username",s);
            List<Member> members = memberMapper.selectByExample(example);

            //校验失败
            if(members.size() == 0)
            {
                checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
                checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
                return checkAuthResponse;
            }
            //校验成功
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            checkAuthResponse.setUserinfo(s);


        }catch (Exception e)
        {
            log.error("UserLoginValidException" + e);
            ExceptionProcessorUtils.wrapperHandlerException(checkAuthResponse,e);
        }


        return checkAuthResponse;
    }

    @Override
    public UserSimpleInfo userLoginGet(String token) {

        String username = JwtTokenUtils.builder().token(token).build().freeJwt();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",username);

        List<Member> members = memberMapper.selectByExample(example);

        UserSimpleInfo userSimpleInfo = new UserSimpleInfo();
        userSimpleInfo.setUid(members.get(0).getId());
        userSimpleInfo.setFile(members.get(0).getFile());

        return userSimpleInfo;
    }

    @Override
    public UserRegisterResponse userRegister(UserRegisterRequest userRegisterRequest) {

        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();

        try {
            //空串验证
            userRegisterRequest.requestCheck();
            //用户名重复验证可以用两种方式：由于表设置了用户名的唯一，强行插入会抛异常，可以捕捉异常再处理
            //也可以在插入前就验证一下
            Example example = new Example(Member.class);
            example.createCriteria().orEqualTo("username",userRegisterRequest.getUserName())
                                    .orEqualTo("email",userRegisterRequest.getEmail());
            List<Member> members = memberMapper.selectByExample(example);
            if(members.size() != 0)
            {
                userRegisterResponse.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
                return userRegisterResponse;
            }

            //如果用户名没问题，先向user表中插入
            Member member = new Member();
            member.setEmail(userRegisterRequest.getEmail());
            member.setUsername(userRegisterRequest.getUserName());
            member.setPassword(userRegisterRequest.getUserPwd());
            member.setCreated(new Date(System.currentTimeMillis()));
            member.setUpdated(new Date(System.currentTimeMillis()));

            int i = memberMapper.insertSelective(member);
            log.info("插入影响行数" + i);

            //插入失败
            if(i == 0)
            {
                userRegisterResponse.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                userRegisterResponse.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return userRegisterResponse;
            }

            //再向激活表中注入
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(userRegisterRequest.getUserName());
            userVerify.setRegisterDate(new Date(System.currentTimeMillis()));
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            userVerify.setUuid(userVerify.getUsername()+ UUID.randomUUID().toString());

            userVerifyMapper.insertSelective(userVerify);

            //最后向目标邮箱中发送邮件
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom("changyb4952@163.com");
            simpleMailMessage.setTo(userRegisterRequest.getEmail());
            simpleMailMessage.setSubject("阿巴阿巴注册激活");
            simpleMailMessage.setText("http://localhost:8080/user/verify?uid=" + userVerify.getUuid() + "&username=" + userVerify.getUsername());

            javaMailSender.send(simpleMailMessage);

            log.info("已向用户发送邮件");
            //设置成功信息码
            userRegisterResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userRegisterResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        }catch (Exception e)
        {
            log.error("UserRegisterException" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userRegisterResponse,e);
        }

        return userRegisterResponse;
    }

    @Override
    public UserVerifyResponse userVerify(UserVerifyRequest userVerifyRequest) {

        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();

        try {
            userVerifyRequest.requestCheck();

            Example example = new Example(UserVerify.class);
            example.createCriteria().andEqualTo("uuid",userVerifyRequest.getUuid())
                                    .andEqualTo("username",userVerifyRequest.getUserName());
            List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);

            //验证失败
            if(userVerifies.size() == 0)
            {
                userVerifyResponse.setCode(SysRetCodeConstants.USER_VERIFY_FAIL.getCode());
                userVerifyResponse.setMsg(SysRetCodeConstants.USER_VERIFY_FAIL.getMessage());
                return userVerifyResponse;
            }
            //验证成功，修改状态
            UserVerify userVerify = userVerifies.get(0);
            userVerify.setIsVerify("Y");
            userVerifyMapper.updateByExampleSelective(userVerify, example);

            Member member = new Member();
            member.setIsVerified("Y");
            Example exampleM = new Example(Member.class);
            exampleM.createCriteria().andEqualTo("username",userVerify.getUsername());
            memberMapper.updateByExampleSelective(member,exampleM);

            //设置成功代码
            userVerifyResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userVerifyResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (Exception e)
        {
            log.error("UserVerifyException" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userVerifyResponse,e);
        }

        return userVerifyResponse;
    }

    /**
     * 购物车 通过username 找ID
     * @param username
     * @return
     */
    @Override
    public Integer cartSelectById(String username) {

        Integer id = memberMapper.cartSelectById(username);
        return id;
    }

    @Override
    public Long getUserIdByToken(String token) {
        String username = JwtTokenUtils.builder().token(token).build().freeJwt();

        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",username);
        List<Member> members = memberMapper.selectByExample(example);

        return members.get(0).getId();
    }

//    @Override
//    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
//        UpdateMemberResponse response = new UpdateMemberResponse();
//        try{
//            request.requestCheck();
//            CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//            checkAuthRequest.setToken(request.getToken());
//            CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest);
//            if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
//                response.setCode(authResponse.getCode());
//                response.setMsg(authResponse.getMsg());
//                return response;
//            }
//            Member member = memberConverter.updateReq2Member(request);
//            int row = memberMapper.updateByPrimaryKeySelective(member);
//            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            log.info("MemberServiceImpl.updateMember effect row :"+row);
//        }catch (Exception e){
//            log.error("MemberServiceImpl.updateMember Occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
//        }
//        return response;
//    }
}
